<template>
  <div class="talk">
    <div id="talk" class="talk"
         style="width: 100%;height: 500px;border: 1px dashed #b4b1b1;margin-bottom: 20px;padding: 20px;box-sizing: border-box;overflow: auto;">
      <div v-for="(item,index) in talkinfo" :key="index" style="height: auto;width: 100%;margin-top: 5px;">
        <div style="width: 100%">
          <div style="width: 100%;height: 40px">
            <el-avatar :class="{'left': item.id!=userId, 'right': item.id==userId}" :src="item.src"></el-avatar>
            <span style="line-height: 40px" :class="{'left': item.id!=userId, 'right': item.id==userId}">{{
                item.name
              }}</span>
          </div>
          <div v-html="item.msg" :class="{'leftse': item.id!=userId, 'rightse': item.id==userId}"
               style="width:45%;border-radius:8px;height: auto;border: 1px solid #cbc7c7;padding:10px;"></div>
        </div>
        <div class="clear"></div>
      </div>
    </div>
    <el-input placeholder="请输入聊天内容" v-model="input3" class="input-with-select">
      <el-button slot="append" @click="websocketsend" icon="el-icon-position"></el-button>
    </el-input>
  </div>
</template>

<script>
export default {
  name: "Talk",
  data: function () {
    return {
      talkinfo: [],
      input3: "",
      userId: null,
      userMsg: {}
    }
  },
  mounted() {
    this.getUserHimself()
  },
  destroyed() {
    this.websock.close() //离开路由之后断开websocket连接
  },
  methods: {
    async getUserHimself() {
      await this.$http.get("/user/getHimself").then(async data => {
        data = data.data
        this.userMsg = data
        this.userId = data.id
        this.initWebSocket(data.id)
      })
    },
    async initWebSocket(userid) { //初始化weosocket
      console.log("建立连接")
      const wsuri = this.$websocket + userid;
      this.url = wsuri
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    async websocketonmessage(e) { //数据接收
      if (e.data.split(":")[0] == this.userId) {
        return
      }
      let speakerMsg
      await this.getUserMsg(e.data.split(":")[0]).then(data => {
        speakerMsg = data
      })
      let src
      await this.getimg(speakerMsg.headPortraitId).then(data => {
        src = data
      })
      let innimsg = {
        msg: e.data.split(":")[1],
        id: e.data.split(":")[0],
        src: src,
        name: speakerMsg.nickname
      }
      this.talkinfo.push(innimsg)

      this.$nextTick(() => {
        let msg = document.getElementById('talk') // 获取对象
        msg.scrollTop = msg.scrollHeight // 滚动高度
      })
    },
    async websocketsend() {//数据发送
      let message = this.input3
      let src
      await this.getimg(this.userMsg.headPortraitId).then(data => {
        src = data
      })
      let innimsg = {
        msg: message,
        id: this.userId,
        src: src,
        name: this.userMsg.nickname
      }
      this.talkinfo.push(innimsg)
      this.websock.send(message);
      this.input3 = ""
      this.$nextTick(() => {
        let msg = document.getElementById('talk') // 获取对象
        msg.scrollTop = msg.scrollHeight // 滚动高度
      })
    },
    websocketonopen() { //连接建立之后执行send方法发送数据

    },
    websocketonerror() {//连接建立失败重连
      // this.initWebSocket();
    },
    websocketclose(e) {  //关闭
      console.log(e)
      console.log('断开连接');
    },
    getUserMsg(id) {
      return new Promise(resolve => {
        this.$http.get("/user/getUserInfoWithoutImportantMsg/" + id).then(data => {
          resolve(data.data)
        })
      })
    },
    getimg(id) {
      return new Promise(resolve => {
        this.$http({
          url: "/file/img/" + id,
          method: "get",
          responseType: "arraybuffer",
        }).then(res => {
          let bytes = new Uint8Array(res);
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          let database = "data:image/png;base64," + window.btoa(storeData);
          resolve(database);
        });
      })
    },
  }
}
</script>

<style scoped>
.talk {
  width: 980px;
  float: right;
}

.clear {
  clear: both;
}

.left {
  float: left;
}

.right {
  float: right;
}

.leftse {
  float: left;
  margin-left: 100px;
  margin-top: 10px;
  word-break: break-all;
  text-align: left;
}

.rightse {
  float: right;
  margin-right: 100px;
  margin-top: 10px;
  word-break: break-all;
  text-align: left;
}

.el-table .cell {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  white-space: normal;
  word-break: break-all;
  line-height: 23px;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap !important;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
::-webkit-scrollbar {
  width: 10px;
  height: 10px;
  background-color: #F5F5F5;
}

/*定义滚动条轨道 内阴影+圆角*/
::-webkit-scrollbar-track {
  box-shadow: inset 0 0 6px rgba(106, 62, 62, 0.3);
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  background-color: #F5F5F5;
}

/*定义滑块 内阴影+圆角*/
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  box-shadow: inset 0 0 6px rgba(0, 0, 0, .1);
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .1);
  background-color: #c8c8c8;
}
</style>